package com.iteaj.iot.server.endpoints;

import com.alibaba.fastjson.JSON;
import com.iteaj.iot.DeviceManager;
import com.iteaj.iot.server.ServerComponentFactory;

import java.util.ArrayList;
import java.util.List;

public class ServerHealthBuilder {

    public static ServerHealthEntity build(ServerComponentFactory factory) {
        ServerHealthEntity.SystemInfo systemInfo = buildSystemInfo();
        ServerHealthEntity.ServerInfo serverInfo = buildServerInfo(factory);
        return new ServerHealthEntity(0, systemInfo, serverInfo);
    }

    public static ServerHealthEntity.SystemInfo buildSystemInfo() {
        return new ServerHealthEntity.SystemInfo();
    }

    public static ServerHealthEntity.ServerInfo buildServerInfo(ServerComponentFactory factory) {
        List<ServerHealthEntity.Component> components = new ArrayList<>();
        factory.getTcpserverComponents().forEach(item -> {
            DeviceManager deviceManager = item.getDeviceManager();
            components.add(new ServerHealthEntity.Component(item.config().getPort(), item.getName()
                    , "tcp", item.startTime(), deviceManager.size(), deviceManager.useSize()));
        });

        factory.getUdpServerComponents().forEach(item -> {
            components.add(new ServerHealthEntity.Component(item.config().getPort(), item.getName(), "udp", item.startTime()));
        });

        return new ServerHealthEntity.ServerInfo(components);
    }

    public static String textBuild(long appStartTime, ServerComponentFactory factory) {
        ServerHealthEntity entity = ServerHealthBuilder.build(factory);
        entity.setStartTime(appStartTime);
        return JSON.toJSONString(entity);
    }

    public static byte[] binaryBuild(long appStartTime, ServerComponentFactory factory) {
        ServerHealthEntity entity = ServerHealthBuilder.build(factory);
        entity.setStartTime(appStartTime);
        return JSON.toJSONBytes(entity);
    }
}
